package com.ethink.framework.common.web.advice;

import com.ethink.framework.common.util.JacksonUtils;
import com.ethink.framework.common.web.properties.WebProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 响应日志打印
 *
 * @author yunduo
 */
@Slf4j
@ControllerAdvice(annotations = RestController.class, basePackages = "com.ethink.**")
public class CustomResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Autowired
    private WebProperties webProperties;

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
                                  ServerHttpResponse response) {
        if (body != null && MediaType.APPLICATION_JSON.equalsTypeAndSubtype(selectedContentType)) {
            String msg = JacksonUtils.toJson(body);
            if (webProperties.getResponseLogMaxLength() != null && StringUtils.isNotBlank(msg) && msg.length() > webProperties.getResponseLogMaxLength()) {
                msg = msg.substring(0, webProperties.getResponseLogMaxLength()) + "...";
            }
            log.info("web_response:{}", msg);
        }
        return body;
    }

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

}